﻿#include "Thread.h"
#include "newWindow.h"
#include "HomePage.h"
//#define _CRT_SECURE_NO_WARNINGS
// 全局互斥锁，用于保护共享数据
std::mutex sharedDataMutex;

//绘制线程函数
void drawingThread(int width, int height, PIMAGE homepage, float scale, int offset_x, int offset_y) {

    mouse_msg msg;
    static bool isClickHandled = false; // 静态变量记录处理状态

    float myscale = 1.0f;
    bool rightButtonDown = false;
    float offsetX = 0.0f, offsetY = 0.0f;
    const float MOVE_SPEED = 100.0f;
    const float base_width = 2560.0f, base_height = 1600.0f;

    ege_enable_aa(true);

    for (; is_run(); delay_fps(60)) {
        cleardevice();

        // 加锁保护共享数据
        {
            std::lock_guard<std::mutex> lock(sharedData.mtx);

            // 处理鼠标事件
            while (mousemsg()) {
                msg = getmouse();
                if (msg.is_right()) {
                    rightButtonDown = msg.is_down() ? true : (msg.is_up() ? false : rightButtonDown);
                }
                if (rightButtonDown && msg.is_wheel()) {
                    myscale = std::clamp(myscale + msg.wheel * 0.002f, 0.9f, 10.0f); // 规定缩放倍数为0.9f-10.0f
                }

            }

            // 处理键盘移动
            if (keystate(VK_LEFT))  offsetX -= MOVE_SPEED;
            if (keystate(VK_RIGHT)) offsetX += MOVE_SPEED;
            if (keystate(VK_UP))    offsetY -= MOVE_SPEED;
            if (keystate(VK_DOWN))  offsetY += MOVE_SPEED;

            // 计算总缩放因子和动态偏移
            float total_scale = scale * myscale;
            int render_width = static_cast<int>(base_width * total_scale);
            int render_height = static_cast<int>(base_height * total_scale);
            int current_offset_x = (width - render_width) / 2;
            int current_offset_y = (height - render_height) / 2;

            // 绘制主背景
            PIMAGE temp_homepage = newimage(render_width, render_height);
            settarget(temp_homepage);
            drawHomePage(render_width, render_height); // 确保drawHomePage适配任意尺寸
            settarget(nullptr);
            putimage(current_offset_x - offsetX, current_offset_y - offsetY, temp_homepage);

            // 计算各仪表的坐标和尺寸
            //lambda 函数
            auto calcInstrumentParams = [&](float base_x, float base_y, float base_size) -> std::tuple<int, int, int> {
                // 计算最终坐标
                const int final_x = current_offset_x + static_cast<int>(base_x * total_scale) - offsetX;
                const int final_y = current_offset_y + static_cast<int>(base_y * total_scale) - offsetY;
                // 计算最终尺寸
                const int final_size = static_cast<int>(base_size * total_scale);
                return { final_x, final_y, final_size };
                };

            // 右侧仪表
            // 使用示例
            //VOR1（航向偏离指示器）
            auto [vor1_x, vor1_y, vor1_size] = calcInstrumentParams(2223.0f, 332.0f, 175.0f);
            drawVOR1(vor1_x, vor1_y, vor1_size, sharedData.vor1hdef, sharedData.vor1dr, sharedData.vor1vdf);

            // VOR2 仪表（下滑道指示仪）
            auto [vor2_x, vor2_y, vor2_size] = calcInstrumentParams(2223.0f, 788.0f, 175.0f);
            drawVOR2(vor2_x, vor2_y, vor2_size, sharedData.vor2hdef, sharedData.vor2dr);

            // ADF 仪表（空中定向方位指示计）
            auto [adf_x, adf_y, adf_size] = calcInstrumentParams(2223.0f, 1248.0f, 175.0f);
            drawADF(adf_x, adf_y, adf_size, 0);
            
            // PHI 仪表(引擎转速表)
            auto [phi_x, phi_y, phi_size] = calcInstrumentParams(1763.0f, 1248.0f, 171.0f);
            drawPHI(phi_x, phi_y, phi_size, sharedData.engineRPM);

            // 左侧仪表
            // FUI(油量表)
            auto [fu_x, fu_y, fq_size] = calcInstrumentParams(232.0f, 786.0f, 111.0f);
            drawFUI(fu_x, fu_y, fq_size, sharedData.left, sharedData.right);

            // TFF(排气温度燃油)
            auto [ff_x, ff_y, ff_size] = calcInstrumentParams(533.0f, 786.0f, 111.0f);
            drawTFF(ff_x, ff_y, ff_size, sharedData.engine);

            // VBT(电流压力）
            auto [vbt_x, vbt_y, vbt_size] = calcInstrumentParams(533.0f, 1101.0f, 120.0f);
            drawVBT(vbt_x, vbt_y, vbt_size, sharedData.I, sharedData.pressure);

            // OTP(油温油压）
            auto [otp_x, otp_y, otp_size] = calcInstrumentParams(232.0f, 1101.0f, 120.0f);
            drawOTP(otp_x, otp_y, otp_size, sharedData.Oilc, sharedData.Oilp);

            // 主要六个表盘
            // AT（姿态仪）
            auto [at_x, at_y, at_size] = calcInstrumentParams(1343.0f, 328.0f, 231.0f);
            drawAT(at_x, at_y, at_size, sharedData.pitch, sharedData.roll);

            // HI（航向仪）
            auto [hi_x, hi_y, hi_size] = calcInstrumentParams(1343.0f, 786.0f, 173.0f);
            drawHI(hi_x, hi_y, hi_size, sharedData.heading);

            // TC（转弯协调仪）
            auto [tc_x, tc_y, tc_size] = calcInstrumentParams(915.0f, 786.0f, 171.0f);
            drawTC(tc_x, tc_y, tc_size, sharedData.turn_rate, sharedData.turn_rate2);

            // AI（空速表）
            auto [ai_x, ai_y, ai_size] = calcInstrumentParams(915.0f, 332.0f, 171.0f);
            drawAI(ai_x, ai_y, ai_size, sharedData.airspeed);

            // AM(高度表）
            auto [am_x, am_y, am_size] = calcInstrumentParams(1764.0f, 332.0f, 163.0f);
            drawAM(am_x, am_y, am_size, sharedData.heightAM);

            // VS(垂直速度表）
            auto [vs_x, vs_y, vs_size] = calcInstrumentParams(1764.0f, 786.0f, 171.0f);
            drawVS(vs_x, vs_y, vs_size, sharedData.verticalSpeed);

            //CNM 时间表
            auto [cnm_x, cnm_y, cnm_size] = calcInstrumentParams(533.0f, 416.0f, 122.0f);
            drawCNM(cnm_x, cnm_y, cnm_size);

            if (keystate(key_mouse_l)) {
                if (!isClickHandled) {       // 首次检测到按下
                    int x, y;
                    mousepos(&x, &y);     // 假设已实现此函数
                    newWindow(x, y, current_offset_x, current_offset_y, offsetX, offsetY, total_scale);
                    isClickHandled = true;   // 标记已处理
                }
            }
            else {
                isClickHandled = false;      // 松开时重置状态
            }

            // 绘制FPS信息（必须在主线程）
            setfont(30, 0, "Tahoma");
            char fps_info[64];
            sprintf_s(fps_info, "FPS: %.1f", getfps());
            setcolor(EGERGB(255, 255, 255));
            outtextxy(100, 10, fps_info);

            delimage(temp_homepage);
        }
    }
}

//未完善部分
// 绘制线程函数
//void drawingThread(int width, int height, PIMAGE homepage, float scale, int offset_x, int offset_y) {
//    mouse_msg msg;
//    static bool isClickHandled = false; // 静态变量记录处理状态
//
//    float myscale = 1.0f;
//    bool rightButtonDown = false;
//    float offsetX = 0.0f, offsetY = 0.0f;
//    const float MOVE_SPEED = 50.0f;
//    const float base_width = 2560.0f, base_height = 1600.0f;
//
//    ege_enable_aa(true);
//
//    for (; is_run(); delay_fps(60)) {
//        cleardevice();
//
//        // 处理鼠标事件
//        while (mousemsg()) {
//            msg = getmouse();
//            if (msg.is_right()) {
//                rightButtonDown = msg.is_down() ? true : (msg.is_up() ? false : rightButtonDown);
//            }
//            if (rightButtonDown && msg.is_wheel()) {
//                myscale = std::clamp(myscale + msg.wheel * 0.001f, 0.6f, 10.0f);
//            }
//        }
//
//        // 处理键盘移动
//        if (keystate(VK_LEFT))  offsetX -= MOVE_SPEED;
//        if (keystate(VK_RIGHT)) offsetX += MOVE_SPEED;
//        if (keystate(VK_UP))    offsetY -= MOVE_SPEED;
//        if (keystate(VK_DOWN))  offsetY += MOVE_SPEED;
//
//        // 计算总缩放因子和动态偏移
//        float total_scale = scale * myscale;
//        int render_width = static_cast<int>(base_width * total_scale);
//        int render_height = static_cast<int>(base_height * total_scale);
//        int current_offset_x = (width - render_width) / 2;
//        int current_offset_y = (height - render_height) / 2;
//
//        // 绘制主背景
//        PIMAGE temp_homepage = newimage(render_width, render_height);
//        settarget(temp_homepage);
//        drawHomePage(render_width, render_height); // 确保drawHomePage适配任意尺寸
//        settarget(nullptr);
//        putimage(current_offset_x - offsetX, current_offset_y - offsetY, temp_homepage);
//
//        // lambda 函数：计算仪表坐标和尺寸
//        auto calcInstrumentParams = [&](float base_x, float base_y, float base_size) -> std::tuple<int, int, int> {
//            const int final_x = current_offset_x + static_cast<int>(base_x * total_scale) - offsetX;
//            const int final_y = current_offset_y + static_cast<int>(base_y * total_scale) - offsetY;
//            const int final_size = static_cast<int>(base_size * total_scale);
//            return { final_x, final_y, final_size };
//            };
//
//        // 右侧仪表 - 读取共享数据时加锁
//        {
//            std::lock_guard<std::mutex> lock1(sharedVor1Data.mtx);
//            std::lock_guard<std::mutex> lock2(sharedVor2Data.mtx);
//
//            auto [vor1_x, vor1_y, vor1_size] = calcInstrumentParams(2223.0f, 332.0f, 175.0f);
//            drawVOR1(vor1_x, vor1_y, vor1_size, sharedVor1Data.vor1hdef, sharedVor1Data.vor1dr);
//
//            auto [vor2_x, vor2_y, vor2_size] = calcInstrumentParams(2223.0f, 788.0f, 175.0f);
//            drawVOR2(vor2_x, vor2_y, vor2_size, sharedVor2Data.vor2hdef, sharedVor2Data.vor2dr);
//        }
//
//        // ADF 仪表和 PHI 仪表（无共享数据依赖）
//        auto [adf_x, adf_y, adf_size] = calcInstrumentParams(2223.0f, 1248.0f, 175.0f);
//        drawADF(adf_x, adf_y, adf_size, 0);
//
//        auto [phi_x, phi_y, phi_size] = calcInstrumentParams(1763.0f, 1248.0f, 171.0f);
//        drawPHI(phi_x, phi_y, phi_size, 0);
//
//        // 左侧仪表
//        {
//            std::lock_guard<std::mutex> lock1(sharedEngineData.mtx);
//            std::lock_guard<std::mutex> lock2(sharedElectricalData.mtx);
//
//            // FUI(油量表)
//            auto [fu_x, fu_y, fq_size] = calcInstrumentParams(232.0f, 786.0f, 111.0f);
//            drawFUI(fu_x, fu_y, fq_size, 0);
//
//            // TFF(排气温度燃油)
//            auto [ff_x, ff_y, ff_size] = calcInstrumentParams(533.0f, 786.0f, 111.0f);
//            drawTFF(ff_x, ff_y, ff_size, 0);
//
//            // VBT(电流压力）
//            auto [vbt_x, vbt_y, vbt_size] = calcInstrumentParams(533.0f, 1101.0f, 120.0f);
//            drawVBT(vbt_x, vbt_y, vbt_size, sharedElectricalData.I, sharedElectricalData.pressure);
//
//            // OTP(油温油压）
//            auto [otp_x, otp_y, otp_size] = calcInstrumentParams(232.0f, 1101.0f, 120.0f);
//            drawOTP(otp_x, otp_y, otp_size, sharedEngineData.Oilc, sharedEngineData.Oilp);
//        }
//
//        // 主要六个表盘 - 使用独立锁保护每个数据结构
//        {
//            std::lock_guard<std::mutex> lock1(sharedAttitudeIndicatorData.mtx);
//            std::lock_guard<std::mutex> lock2(sharedHeadingIndicatorData.mtx);
//            std::lock_guard<std::mutex> lock3(sharedTurnCoordinatorData.mtx);
//            std::lock_guard<std::mutex> lock4(sharedAirspeedIndicatorData.mtx);
//            std::lock_guard<std::mutex> lock5(sharedAltimeterData.mtx);
//            std::lock_guard<std::mutex> lock6(sharedVerticalSpeedIndicatorData.mtx);
//
//            // AT（姿态仪）
//            auto [at_x, at_y, at_size] = calcInstrumentParams(1343.0f, 328.0f, 231.0f);
//            drawAT(at_x, at_y, at_size, sharedAttitudeIndicatorData.pitch, sharedAttitudeIndicatorData.roll);
//
//            // HI（航向仪）
//            auto [hi_x, hi_y, hi_size] = calcInstrumentParams(1343.0f, 786.0f, 173.0f);
//            drawHI(hi_x, hi_y, hi_size, sharedHeadingIndicatorData.heading);
//
//            // TC（转弯协调仪）
//            auto [tc_x, tc_y, tc_size] = calcInstrumentParams(915.0f, 786.0f, 171.0f);
//            drawTC(tc_x, tc_y, tc_size, sharedTurnCoordinatorData.turn_rate, sharedTurnCoordinatorData.turn_rate2);
//
//            // AI（空速表）
//            auto [ai_x, ai_y, ai_size] = calcInstrumentParams(915.0f, 332.0f, 171.0f);
//            drawAI(ai_x, ai_y, ai_size, sharedAirspeedIndicatorData.airspeed);
//
//            // AM(高度表）
//            auto [am_x, am_y, am_size] = calcInstrumentParams(1764.0f, 332.0f, 163.0f);
//            drawAM(am_x, am_y, am_size, sharedAltimeterData.heightAM);
//
//            // VS(垂直速度表）
//            auto [vs_x, vs_y, vs_size] = calcInstrumentParams(1764.0f, 786.0f, 171.0f);
//            drawVS(vs_x, vs_y, vs_size, sharedVerticalSpeedIndicatorData.verticalSpeed);
//        }
//
//        // CNM 时间表（无共享数据依赖）
//        auto [cnm_x, cnm_y, cnm_size] = calcInstrumentParams(533.0f, 416.0f, 122.0f);
//        drawCNM(cnm_x, cnm_y, cnm_size);
//
//        // 鼠标点击处理
//        if (keystate(key_mouse_l)) {
//            if (!isClickHandled) {       // 首次检测到按下
//                int x, y;
//                mousepos(&x, &y);     // 假设已实现此函数
//                newWindow(x, y, current_offset_x, current_offset_y, offsetX, offsetY, total_scale);
//                isClickHandled = true;   // 标记已处理
//            }
//        }
//        else {
//            isClickHandled = false;      // 松开时重置状态
//        }
//
//        delimage(temp_homepage);
//    }
//}